<template>
    <div class="product-list-container">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>商品列表</span>
            <el-button type="primary" @click="$router.push('/products/add')">添加商品</el-button>
          </div>
        </template>
        
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
          </el-form-item>
          
          <el-form-item label="商品分类">
            <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
              <el-option label="毛绒玩具" value="plush" />
              <el-option label="智能玩具" value="smart" />
              <el-option label="互动玩具" value="interactive" />
              <el-option label="玩偶配件" value="accessories" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="价格区间">
            <el-input-number v-model="searchForm.minPrice" :min="0" :precision="2" placeholder="最低价" />
            <span class="mx-2">-</span>
            <el-input-number v-model="searchForm.maxPrice" :min="0" :precision="2" placeholder="最高价" />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
        
        <!-- 商品表格 -->
        <el-table 
          :data="productList"
          border
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="id" label="商品ID" width="80" />
          
          <el-table-column label="商品图片" width="100">
            <template #default="scope">
              <el-image
                :src="getImageUrl(scope.row.image)"
                :preview-src-list="[getImageUrl(scope.row.image)]"
                fit="cover"
                style="width: 60px; height: 60px"
              />
            </template>
          </el-table-column>
          
          <el-table-column prop="name" label="商品名称" min-width="180" show-overflow-tooltip />
          
          <el-table-column prop="category" label="分类" width="120">
            <template #default="scope">
              <el-tag>{{ scope.row.category }}</el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="price" label="价格" width="100">
            <template #default="scope">
              ¥{{ scope.row.price }}
            </template>
          </el-table-column>
          
          <el-table-column prop="stock" label="库存" width="80" />
          
          <el-table-column prop="sales" label="销量" width="80" />
          
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-switch
                v-model="scope.row.is_hot"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
                active-text="热门"
                inactive-text="普通"
              />
            </template>
          </el-table-column>
          
          <el-table-column fixed="right" label="操作" width="150">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button link type="primary" size="small" @click="viewDetail(scope.row)">查看</el-button>
              <el-button link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { getProductList, deleteProduct, updateProduct } from '../../api/product'
  
  const router = useRouter()
  const loading = ref(false)
  // 添加一个标志位表示组件是否已销毁
  const isComponentUnmounted = ref(false)
  
  // 搜索表单
  const searchForm = reactive({
    name: '',
    category: '',
    minPrice: null,
    maxPrice: null
  })
  
  // 分页信息
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })
  
  // 商品列表数据
  const productList = ref([])
  
  // 获取商品列表数据
  const fetchProductList = async () => {
    loading.value = true
    
    try {
      const params = {
        page: pagination.currentPage,
        limit: pagination.pageSize,
        name: searchForm.name,
        category: searchForm.category,
        minPrice: searchForm.minPrice,
        maxPrice: searchForm.maxPrice
      }
      
      const res = await getProductList(params)
      productList.value = res.items
      pagination.total = res.total
    } catch (error) {
      ElMessage.error('获取商品列表失败: ' + error.message)
    } finally {
      loading.value = false
    }
  }
  
  // 搜索
  const handleSearch = () => {
    pagination.currentPage = 1
    fetchProductList()
  }
  
  // 重置搜索
  const resetSearch = () => {
    Object.keys(searchForm).forEach(key => {
      searchForm[key] = typeof searchForm[key] === 'string' ? '' : null
    })
    handleSearch()
  }
  
  // 编辑商品
  const handleEdit = (row) => {
    router.push(`/products/edit/${row.id}`)
  }
  
  // 查看商品详情
  const viewDetail = (row) => {
    router.push(`/products/edit/${row.id}?view=true`)
  }
  
  // 删除商品
  const handleDelete = (row) => {
    ElMessageBox.confirm(`确认删除商品"${row.name}"吗？`, '删除确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await deleteProduct(row.id)
        ElMessage.success('删除成功')
        fetchProductList()
      } catch (error) {
        ElMessage.error('删除失败: ' + error.message)
      }
    }).catch(() => {})
  }
  
  // 组件卸载前设置标志位
  onBeforeUnmount(() => {
    isComponentUnmounted.value = true
  })
  
  // 修改商品状态
  const handleStatusChange = async (row) => {
    // 如果组件已经卸载，不执行操作
    if (isComponentUnmounted.value) return
    
    const statusText = row.is_hot === 1 ? '热门' : '普通'
    
    try {
      // 确保row对象存在再执行操作
      if (!row) return
      
      // 只更新is_hot字段
      await updateProduct(row.id, { is_hot: row.is_hot })
      
      // 再次检查组件是否已卸载
      if (isComponentUnmounted.value) return
      
      ElMessage.success(`商品已设为${statusText}`)
    } catch (error) {
      // 如果组件已卸载，不执行后续操作
      if (isComponentUnmounted.value) return
      
      // 确保row对象仍然存在再回滚状态
      if (row) {
        row.is_hot = row.is_hot === 1 ? 0 : 1  // 失败时回滚状态
      }
      ElMessage.error('状态更新失败: ' + error.message)
    }
  }
  
  // 分页大小变化
  const handleSizeChange = (size) => {
    pagination.pageSize = size
    fetchProductList()
  }
  
  // 页码变化
  const handleCurrentChange = (page) => {
    pagination.currentPage = page
    fetchProductList()
  }
  
  // 添加图片URL处理函数
  const getImageUrl = (image) => {
    if (!image) return '';
    
    // 检查是否已经是完整的URL
    if (image.startsWith('http')) return image;
    
    // 服务器基础URL
    const serverBaseUrl = 'http://localhost:5000';
    
    // 确保路径正确
    const path = image.startsWith('/') ? image : `/${image}`;
    
    // 如果是相对路径，添加uploads前缀
    if (!path.startsWith('/uploads') && !path.startsWith('/api')) {
      return `${serverBaseUrl}/uploads${path}`;
    }
    
    return `${serverBaseUrl}${path}`;
  }
  
  onMounted(() => {
    fetchProductList()
  })
  </script>
  
  <style scoped>
  .product-list-container {
    padding: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .mx-2 {
    margin: 0 5px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  </style>